package com.dushibao.manage.advert;

import com.alibaba.fastjson2.JSON;
import com.dushibao.entity.Advert;
import com.dushibao.service.AdvertService;
import com.dushibao.service.impl.AdvertServiceImpl;
import com.dushibao.view.ModelAndView;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/advert/add")
public class AddServlet extends HttpServlet {
    AdvertService advertService = new AdvertServiceImpl();

    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        Map<String,Object> maps = new HashMap<>();

        //如果有id说明是编辑
        if(id !=null && id.length()>0){
            Advert obj = advertService.getById(Long.parseLong(id));

            maps.put("editObj",obj);
        }

        ModelAndView mv = new ModelAndView("advert/add",maps);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        BufferedReader bw = req.getReader();
        String json = bw.readLine();

        Advert advert = JSON.parseObject(json, Advert.class);

        Integer ret = advertService.saveOrUpdate(advert);
        resp.getWriter().write(ret.toString());
    }
}
